<template>
	<div class="LedtContent">
		<div class="form-view">
			<!-- 装置 -->
			<div class="form-row">
				<div class="form-row-label">
					{{ $t("message.bhView.leftComponents.device") }}
				</div>
				<div class="form-row-right-content">
					<el-select v-model="valuePlant" :placeholder="$t('message.bhView.label.placeholderSearch')
						" class="form-ipt" @change="PlantChange()" @focus="getPlantApi(1, 1000)">
						<el-option v-for="item in plantOptions" :key="item.pltCode" :label="item.pltName"
							:value="item.pltCode"></el-option>
					</el-select>
				</div>
			</div>

			<!-- 対象 -->
			<div class="form-row">
				<div class="form-row-label">
					{{ $t("message.bhView.leftComponents.object") }}
				</div>
				<div class="form-row-right-content">
					<el-select v-model="radio" :placeholder="$t('message.bhView.label.placeholderSearch')
						" class="form-ipt" @change="radioChange" @focus="getPlantApi(1, 1000)">
						<el-option :label="$t('message.bhView.leftComponents.machine')" value="1"></el-option>

						<el-option :label="$t('message.bhView.leftComponents.piping')" value="2"></el-option>
					</el-select>
				</div>
			</div>

			<!-- 搜索 -->
			<div class="form-row">
				<div class="form-row-label seach">
					<i class="el-icon-search" @click="ctgVauleSearch"></i>
				</div>
				<div class="form-row-right-content">
					<el-input v-model="ctgVaule" placeholder="" class="form-ipt"
						@keyup.enter.native="ctgVauleSearch"></el-input>
				</div>
			</div>
		</div>

		<!-- 机器番号 -->
		<div class="machine-number">
			<div class="title">
				<span v-if="radio == '1'">{{
					$t("message.bhView.leftComponents.MachineSerialNumber")
				}}</span>
				<span v-if="radio == '2'">ラインNo</span>
			</div>
			<div class="machine-number-body">
				<div class="Item" v-for="(Item, index) in drwMgtData" :key="Item.dmgCode"
					@click="ClickTableRow(Item, index)" :class="index == itemActive ? 'ItemActive' : ''">
					<div class="ItemID">{{ index + 1 }}</div>
					<div class="ItemName">
						{{ radio == "1" ? Item.macName : Item.name }}
					</div>

					<div class="itemStatus">
						<el-image style="
								width: 17px;
								height: 17px;
								padding: 2px;
								margin-top: 4px;
							" :src="Item.isRaMe ? checkImg : uncheckImg" fit="fill"></el-image>
					</div>
				</div>
			</div>
		</div>

		<!-- 选中的构件号 -->
		<div class="select-number">
			<ux-grid ref="multipleTable" :data="macNumberData" style="width: 100%" :header-cell-style="{
				color: 'rgba(0, 0, 0, 0.85)',
				fontSize: '14px',
				textAlign: 'left',
				fontWeight: 'bold',
				padding: 0,
				height: '32px',
			}" :cell-style="{
					color: 'rgba(96,98,102,1)',
					fontSize: '14px',
					textAlign: 'left',
					padding: 0,
					height: '32px',
				}" :row-style="{
					color: 'rgba(96,98,102,1)',
					fontSize: '13px',
					textAlign: 'left',
					padding: 0,
					height: '32px',
				}" @current-change="handleCurrentChange" @selection-change="handleSelectionChange" highlight-current-row
				:height="tableHeight" :element-loading-text="$t('message.bhView.loading')">
				<template slot="empty"> No data </template>
				<ux-table-column type="checkbox" width="55"> </ux-table-column>
				<ux-table-column property="partsCode" :title="$t(
					'message.smartPidPage.threeDLeftContent.pidTableColTitle1'
				)
					">
					<template slot-scope="scope">
						<p @click="
							handleSelectNumberNameClick(
								scope.$rowIndex,
								scope.row
							)
							">
							{{ scope.row.partsCode }}
						</p>
					</template>
				</ux-table-column>

				<ux-table-column :title="$t(
					'message.smartPidPage.threeDLeftContent.pidTableColTitle2'
				)
					" width="60">
					<template slot-scope="scope">
						<el-button @click="
							handleSelectNumberDelClick(
								scope.$rowIndex,
								scope.row,
								scope
							)
							" type="text" size="small" :disabled="isEdit">{{ $t("message.public.delete") }}</el-button>
					</template>
				</ux-table-column>
			</ux-grid>
			<div class="select-info">
				<div class="info">
					{{
						$t("message.smartPidPage.threeDLeftContent.footTotal") +
						drwMgtData.length +
						$t("message.smartPidPage.threeDLeftContent.footerUnit")
					}}
				</div>

				<div class="info">
					{{
						$t("message.smartPidPage.threeDLeftContent.footPart") +
						raMeData.length +
						$t("message.smartPidPage.threeDLeftContent.footerUnit")
					}}
				</div>
			</div>
		</div>

		<!-- 底部信息 -->
		<div class="bh-footer">
			<el-button class="select-btn gray" :disabled="isEdit" @click="onDeleteClick">
				{{ $t("message.public.delete") }}
			</el-button>

			<el-button class="select-btn gray" :disabled="isEdit" @click="onCancelClick">
				{{ $t("message.public.cancel") }}
			</el-button>

			<el-button class="select-btn blue" :class="isEdit ? 'opa' : ''" :disabled="isEdit" @click="onConfirmClick">
				保存
			</el-button>
		</div>
	</div>
</template>

<script>
import {
	getPlant,
	getMachine,
	getTotDimensInteractive,
	addTotDimensInteractive,
	getRelationMachine
} from "@/api/api";
import eventBus from "@/eventBus/bus";
import Template from "../../template.vue";
// import $ from "jquery";
// 导出模块
export default {
	// 模块名字
	name: "LeftContent",
	props: {
		// numberData: Number,
		// activeName: String,
		// styleOptionsValue: Number,
		selectNumberListData: [],
		isEdit: Boolean
	},
	// 模块数据
	data() {
		let _self = this;
		//数据
		return {
			timer: null,

			radio: "1", // mactype 单选
			radio: _self.$store.state.threeRelationMacType.toString(), // mactype 单选
			plantOptions: [], // 装置下拉
			valuePlant: "", // 装置选择值
			drwMgtData: [], // 机器列表
			raMeData: [], // 已绑定的机器
			number: 0, // 机器数量
			itemActive: null, // 选中机器

			ctgVaule: "", // 搜索输入关键字

			// 机器构件数组
			macNumberData: [],

			mCheckedMacIdArray: [],

			// 是否处理构件选中事件
			doThingWhenSelectNumber: true,

			tableHeight: 275,

			checkImg: require("@/assets/img/checkbox_sel.png"),
			uncheckImg: require("@/assets/img/checkbox_unsel.png"),
		};
	},
	// 注册组件
	components: { Template },
	// 监听指定值，只有指定值变化，才会触发
	watch: {
		macNumberData: {
			handler(val, oval) {
				this.$nextTick(() => {
					let tempSelectList = [];
					val.forEach((valItem) => {
						let tempSelect = {};
						tempSelect.row = valItem;
						tempSelect.selected = valItem.isSelect;
						tempSelectList.push(tempSelect);
					});
					this.$refs.multipleTable.toggleRowSelection(tempSelectList);

					if (val.length == 0) {
						this.mCheckedMacIdArray = [];
					}
				});
			},
			deep: true,
		},

		mCheckedMacIdArray(nVal, oVal) {
			console.log(`watch mCheckedMacIdArray ---  ---`, nVal);
			this.$emit("checkMacArrayChange", nVal);
		},
	},
	// 里面的函数只有调用才会执行（实时计算）里面是定义的方法
	methods: {
		// 获取装置
		getPlantApi(pageIndex, pageSize, isInit = false) {
			let dataJson = {
				pltCode: 0,
				platName: "",
				pageIndex: pageIndex,
				pageSize: pageSize,
			};
			getPlant(dataJson).then((res) => {
				this.plantOptions = [];
				if (res.data.code != 0) {
					return;
				}
				this.plantOptions = res.data.data;

				if (isInit) {
					if (this.$store.state.threeRelationPltCode) {
						this.valuePlant =
							this.$store.state.threeRelationPltCode;
					} else {
						this.valuePlant = this.plantOptions[0].pltCode;
						this.$store.commit(
							"changeThreeRelationPltCode",
							this.valuePlant
						);
					}

					this.plantOptions.forEach((Item) => {
						if (Item.pltCode == this.valuePlant) {
							this.$store.commit(
								"changeThreeRelationPlantName",
								Item.pltName
							);
						}
					});
					this.getMachineApi("", this.ctgVaule, "", 1, 1000);
					// this.getRelationMachineApi();

				}
			});
		},
		//获取机器/配管
		getMachineApi(macCode, macName, impCode, pageIndex, pageSize) {
			this.$store.commit("changeThreeRelationMacName", "");
			this.$store.commit("changeThreeRelationMacNameb", "");
			this.drwMgtData = [];
			this.number = 0;
			let dataJson = {
				macCode: macCode == "" ? 0 : macCode,
				macName: macName,
				pltCode:
					this.$store.state.threeRelationPltCode == ""
						? 0
						: this.$store.state.threeRelationPltCode,
				macType: parseInt(this.$store.state.threeRelationMacType),
				ctgCode: 0,
				impCode: impCode == "" ? 0 : impCode,
				lawCode: 0,
				pageIndex: pageIndex,
				pageSize: 9999,
			};
			getMachine(dataJson).then((res) => {
				if (res.data.code != 0) {
					// 机器列表异常 通知上层页面选中为空
					this.$store.commit("changeThreeRelationMacName", "");
					this.$store.commit("changeThreeRelationMacNameb", "");
					this.getThreeNumberList(null);
					return;
				}

				this.drwMgtData = res.data.data;

				this.number = res.data.count;
				this.itemActive = 0;
				this.$store.commit(
					"changeThreeRelationMacName",
					this.drwMgtData[0].macName
				);
				this.$store.commit(
					"changeThreeRelationMacNameb",
					this.drwMgtData[0].name
				);
				this.getThreeNumberList(this.drwMgtData[0]);
				this.getRelationMachineApi();

				console.log(this.drwMgtData, "---");

			});
		},
		// 获取绑定机器
		getRelationMachineApi() {
			let dataJson = {
				macType: parseInt(this.$store.state.threeRelationMacType)
			};
			getRelationMachine(dataJson).then(res => {
				if (res.data.code != 0) {
					return
				}
				this.raMeData = res.data.data;
				console.log(this.raMeData, "已绑定的机器")
				this.drwMgtData.forEach((i, v) => {
					i.isRaMe = false;
					this.raMeData.forEach((j, k) => {
						if (i.macCode == j.dmgCode) {
							i.isRaMe = true;
						}
					})
				})
				// 页面已渲染机器列表，新增绑定状态后强制更新页面
				this.$forceUpdate()
			})
		},

		getThreeNumberList(inMacData) {
			this.mCheckedMacIdArray = [];
			this.macNumberData = [];
			if (inMacData == null) return;
			getTotDimensInteractive({
				dmgCode: inMacData.macCode,
			}).then((res) => {
				if (res.data.code == 0) {
					this.macNumberData = res.data.data;
				}
			});
		},

		saveThreeNumberList() {
			// debugger
			addTotDimensInteractive({
				dmgCode: this.drwMgtData[this.itemActive].macCode,
				partsCode: this.mCheckedMacIdArray,
			}).then((res) => {
				if (res.data.code == 0) {
					this.getThreeNumberList(this.drwMgtData[this.itemActive]);
					this.$notify({
						title: "提示",
						message: this.$t(
							"message.smartPidPage.threeDLeftContent.warning2"
						),
						duration: 3000,
					});
					this.getRelationMachineApi();
				} else {
					this.getThreeNumberList(this.drwMgtData[this.itemActive]);
					this.$notify({
						title: "提示",
						message: this.$t(
							"message.smartPidPage.threeDLeftContent.warning3"
						),
						duration: 3000,
					});
				}
			});
		},

		//装置筛选
		PlantChange() {
			// 装置选择后更新装置code 和 名称
			this.$store.commit("changeThreeRelationPltCode", this.valuePlant);
			this.plantOptions.forEach((Item) => {
				if (Item.pltCode == this.valuePlant) {
					this.$store.commit(
						"changeThreeRelationPlantName",
						Item.pltName
					);
				}
			});
			this.getMachineApi("", "", "", 1, 1000);
			this.itemActive = null;
		},
		//点击表格行
		ClickTableRow(row, index) {
			this.itemActive = index;

			this.$store.commit("changeThreeRelationMacName", row.macName);
			this.$store.commit("changeThreeRelationMacNameb", row.name);

			this.getThreeNumberList(row);
		},
		ctgVauleSearch() {
			this.getMachineApi("", this.ctgVaule, "", 1, 1000);
		},
		//切换机器或者配管 数据刷新
		radioChange(radio) {
			// 更新状态 
			this.ctgVaule = "";

			this.$store.commit("changeThreeRelationMacType", radio);
			this.getMachineApi("", this.ctgVaule, "", 1, 1000);
		},

		/**
		 *
		 */
		handleSelectNumberNameClick(inIdex, inData) {
			this.$emit("handleCurrentChange", inData);
		},

		/**
		 * 构件削除
		 */
		handleSelectNumberDelClick(inIdex, inData, ins) {
			console.log("handleSelectNumberDelClick --- ", inData);
			// delete in 选中列表
			let tempStrIndex = this.mCheckedMacIdArray.findIndex((e) => {
				return e == inData.partsCode;
			});

			if (tempStrIndex != -1)
				this.mCheckedMacIdArray.splice(tempStrIndex, 1);

			// delete in 选中列表
			let tempAllIndex = this.macNumberData.findIndex((e) => {
				return e.partsCode == inData.partsCode;
			});

			if (tempAllIndex != -1) this.macNumberData.splice(tempAllIndex, 1);
		},

		/**
		 * 构件多选
		 */
		handleSelectionChange(val) {
			console.log(`handleSelectionChange  ---   ---`);

			this.mCheckedMacIdArray = [];
			this.macNumberData.forEach((le) => {
				let tempindex = val.findIndex((se) => {
					return le.partsCode == se.partsCode;
				});

				if (tempindex != -1) {
					le.isSelect = true;
					this.mCheckedMacIdArray.push(le.partsCode);
				} else le.isSelect = false;
			});

			console.log(
				`handleSelectionChange  ---  end ---`,
				this.macNumberData
			);
		},

		/**
		 * 构件单选
		 */
		handleCurrentChange(val) { },

		onThreeDElementClick(inId) {
			if (
				this.$store.state.threeRelationMacName == "" ||
				this.$store.state.threeRelationMacNameb == ""
			) {
				this.$notify({
					title: "提示",
					message: this.$t(
						"message.smartPidPage.threeDLeftContent.warning1"
					),
					duration: 3000,
				});

				return;
			}

			console.log(`onThreeDElementClick  ---   ---`);

			let tempObjIndex = this.macNumberData.findIndex((e) => {
				return inId == e.partsCode;
			});

			if (tempObjIndex != -1) {
				this.macNumberData[tempObjIndex].isSelect = true;
				return;
			}

			this.macNumberData.push({
				id: inId,
				partsCode: inId,
				isSelect: true,
			});
		},

		onDeleteClick() {
			// macNumberData: [],
			// mCheckedMacIdArray: [],
			this.mCheckedMacIdArray.forEach((checkId) => {
				let tempIndex = this.macNumberData.findIndex((allitem) => {
					return allitem.partsCode == checkId;
				});

				if (tempIndex != -1) {
					this.macNumberData.splice(tempIndex, 1);
				}
			});
		},

		onCancelClick() {
			this.getThreeNumberList(this.drwMgtData[this.itemActive]);
		},

		onConfirmClick() {
			this.saveThreeNumberList();
		},
	},
	// 创建前状态(里面是操作)
	beforeCreate() { },
	// 创建完毕状态(里面是操作)
	created() {
		//默认添加装置
		this.getPlantApi(1, 1000, true);

	},
	// 挂载前状态(里面是操作)
	beforeMount() { },
	// 挂载结束状态(里面是操作)
	mounted() {
		this.tableHeight = $(".select-number").height() - 34.5;

		eventBus.$on("getOneData", () => {
			// if(e){
			// 	clearInterval(this.timer);
			// 	return
			// }
			// this.timer = setInterval(() => {
			this.ClickTableRow(this.drwMgtData[0], 0)
			// }, 1000);
		})
	},
	// 更新前状态(里面是操作)
	beforeUpdate() { },
	// 销毁前状态(里面是操作)
	beforeDestroy() {
		eventBus.$off("getOneData")
	},
	// 销毁完成状态(里面是操作)
	destroyed() { },
	// 更新完成状态(里面是操作)
	updated() {
		// 使用querySelectorAll选中所有带有.elx-cell--checkbox类的元素
		var elements = document.querySelectorAll('.elx-cell--checkbox');

		// 遍历这些元素  
		elements.forEach(function (element) {
			// 修改每个元素的title属性  
			element.setAttribute('title', '');
		})
	},
};
</script>
<style lang="scss" scoped>
.LedtContent {
	width: 100%;
	height: 100%;
	//     background: rosybrown;
	display: flex;
	justify-content: space-between;
	flex-direction: column;
}

.form-view {
	padding-right: 24px;

	box-sizing: border-box;

	.form-row {
		width: 100%;
		height: 24px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 12px;

		.seach {
			width: 24px;
			height: 24px;
			border-radius: 4px;
			border: 1px solid #d9d9d9;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
		}

		.form-row-label {
			color: rgba(0, 0, 0, 0.85);
			//   font-weight: 500;
		}

		.form-row-right-content {
			width: 85%;

			.form-ipt {
				width: 100%;
				height: 24px;

				::v-deep .el-input__inner {
					height: 24px;
					background: #fff;
				}

				::v-deep .el-input__icon {
					line-height: 24px;
				}
			}

			.ClearBtn {
				min-width: 66px;
				height: 24px;
				border-radius: 4px;
				display: flex;
				justify-content: center;
				align-items: center;
				border: 1px solid #eaeaeb;
				background: #106ebe;
				color: #fff;
				float: right;
			}
		}
	}

	.form-checkbox {
		padding: 0 0 12px 44px;
	}
}

.machine-number {
	width: calc(100% - 24px);
	height: calc(47% - 0px);
	border: 1px solid #c3c3c3;
	margin-left: 0px;
	box-sizing: border-box;

	.title {
		width: 100%;
		height: 32px;
		font-size: 14px;
		color: rgba(0, 0, 0, 0.85);
		background: #e9e9e9;
		display: flex;
		align-items: center;
		justify-content: center;
		border-bottom: 1px solid rgba(195, 195, 195, 0.3);
	}

	.machine-number-body {
		width: 100%;
		height: calc(100% - 32px);
		overflow: hidden;
		overflow-y: auto;

		.Item {
			display: flex;
			align-items: center;
			justify-content: flex-start;
			width: 100%;
			height: 24px;
			cursor: pointer;
			border-bottom: 1px solid rgba(195, 195, 195, 0.3);
			background: #ffffff;
			transition: 0.5s;

			.ItemID {
				width: 71px;
				height: 24px;
				border-right: 1px solid rgba(195, 195, 195, 0.3);
				display: flex;
				align-items: center;
				justify-content: center;
				color: rgba(0, 0, 0, 0.85);
			}

			.ItemName {
				padding-left: 24px;
				height: 100%;
				color: rgba(0, 0, 0, 0.65);
				display: flex;
				align-items: center;
				border-right: 1px solid rgba(195, 195, 195, 0.3);
				width: 100%;
			}

			.itemStatus {
				width: 71px;
				height: 24px;
				padding-left: 17px;
			}
		}

		.Item:hover {
			background: rgb(255, 241, 240);
		}

		.ItemActive {
			background: rgb(255, 241, 240);
		}
	}
}

.select-number {
	width: calc(100% - 24px);
	height: calc(28% - 0px);
	border: 1px solid #c3c3c3;
	margin-left: 0px;
	box-sizing: border-box;

	.select-info {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-around;
		width: calc(100%);
		background-color: #edeeef;
		padding: 6px 0px;

		.info {
			font-size: 14px;
			color: rgba(0, 0, 0, 0.65);
		}
	}
}

.bh-footer {
	height: 38px;
	display: flex;
	align-items: center;
	justify-content: space-between;

	padding: 0px 24px;
	padding-left: 0px;

	.select-btn {
		width: 90px;
		height: 30px;
		border: 1px solid #eaeaeb;
		border-radius: 4px;
		line-height: 2px;
	}

	.select-btn:nth-child(2) {
		transform: translateX(-25px)
	}

	.gray {
		// color: rgb(89, 89, 89);
		background: #e9e9e9;
	}

	.blue {
		color: #fff;
		background: #106ebe;
	}

	.red {
		color: #fff;
		background: #bc000f;
	}

	.opa {
		opacity: .5;
	}
}

::v-deep .el-radio {
	margin-right: 24px;
}

::v-deep .el-radio:last-child {
	margin-right: 0;
}
</style>
